package com.atguigu.yygh.msm.controller;


import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MsmService msmService;

    //发送验证码的方法
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        //1.从redis获取验证码,如果可以获取到 直接返回
        String redisCode = redisTemplate.opsForValue().get(phone);
        //为了省短信
        if (!StringUtils.isEmpty(redisCode)) {
            return R.ok();
        }
        //2.如果获取不到,生成验证码 进行发送
        String code = RandomUtil.getFourBitRandom();
        //验证码发送
        boolean flag = msmService.sendMsmDx(phone, code);
        //3 发送之后，把发送之后验证码放到redis里面，设置有效时间
        if (flag) {
            redisTemplate.opsForValue().set(phone, code, 120, TimeUnit.SECONDS);
            return R.ok();
        } else {
            return R.error();
        }
    }
}
